package cn.lili.modules.lucene;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 16:27 2025/6/23
 */
@Slf4j
@Component
public class IndexHealthMonitor {
    private static final long ERROR_THRESHOLD = 30 * 60 * 1000; // 30分钟
    private static final long REBUILD_THRESHOLD = 24 * 60 * 60 * 1000; // 24小时

    @Autowired
    private IndexStateManager stateManager;
    @Autowired
    private OnDemandIndexInitializer indexInitializer;

    @Scheduled(fixedRate = 300_000) // 每5分钟
    public void monitorIndexHealth() {
        switch (stateManager.getCurrentState()) {
            case ERROR:
                handleErrorState();
                break;
            case READY:
                checkRebuildNeeded();
                break;
            default:
                // 其他状态不处理
        }
    }

    private void handleErrorState() {
        if (stateManager.timeSinceLastError() > ERROR_THRESHOLD) {
            log.warn("索引错误状态已持续30分钟，尝试自动恢复...");
            indexInitializer.forceRebuild();
        }
    }

    private void checkRebuildNeeded() {
        if (stateManager.timeSinceLastRebuild() > REBUILD_THRESHOLD) {
            log.info("索引已超过24小时未重建，执行预防性重建...");
            indexInitializer.forceRebuild();
        }
    }
}